<template>
  <el-dialog v-loading="loading" :append-to-body="true" :close-on-click-modal="false" :visible.sync="visable" title="导入流程" width="400px" top="5vh" @close="closeDlg">

    <div>
      <el-upload
        ref="upload"
        drag
        action="sys/process/impProcess"
        :limit="1"
        accept=".bpmn, .xml"
        :headers="headers"
        :before-upload="beforeFileUpload"
        :auto-upload="false"
        name="bpmnFile"
        :data="form"
        :on-success="handleFileSuccess"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将流程文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">只能上传“bpm”或“xml”格式文件</div>
      </el-upload>
    </div>
    <el-row>
      <p class="orange">说明：流程ID必需要与流程文件的ID相符；若与已有流程的ID相同则更新并部署流程，否则新建并部署流程。<br>请谨慎操作！！！</p>
    </el-row>
    <el-form ref="xform" :model="form" :rules="rules" size="small" label-width="80px">
      <el-form-item label="流程ID" prop="key">
        <el-input v-model="form.key" maxlength="30" />
      </el-form-item>
      <el-form-item label="流程名称" prop="name">
        <el-input v-model="form.name" maxlength="40" />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from '@/utils/auth'
export default {
  name: 'ProcessDefVOForm',
  data() {
    return {
      headers: {
        'Authorization': 'Bearer ' + getToken()
      },
      loading: false,
      visable: false,
      form: {
        name: '',
        key: ''
      },
      rules: {
        key: [
          { required: true, message: '请输入流程ID', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    resetFields() {
      this.$refs.upload.clearFiles()
      this.$refs['xform'].resetFields()
      this.form = {
        name: '',
        key: ''
      }
    },
    cancel() {
      this.closeDlg()
    },
    show() {
      this.visable = true
    },
    doSubmit() {
      this.$refs['xform'].validate((valid) => {
        if (valid) {
          this.loading = true
          this.$refs.upload.submit()
          this.loading = false
        }
      })
    },
    beforeFileUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 10MB!')
      }
      return isLt2M
    },
    handleFileSuccess: function(res) {
      if (res.code === 200) {
        this.$parent.getList()
        this.closeDlg()
      } else {
        this.$message.error('导入失败！' + res.message)
      }
    },
    closeDlg() {
      this.visable = false
      this.resetFields()
    }
  }
}
</script>
